package com.zhuzi.guicollect.jsl.page;

import com.zhuzi.guicollect.jsl.JslQuestion;
import com.zhuzi.guicollect.utils.HttpUtils;
import com.zhuzi.guicollect.utils.SysUtils;
import io.mikael.urlbuilder.UrlBuilder;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @Author: MI
 * @Date: 2021/10/24/21:10
 * @Description:
 */
public class BasePage {
    public static String questionPage = "https://www.jisilu.cn/question/id-%s__sort_key-__sort-DESC__uid-%s__page-%s";
    public static String urlForComment = "https://www.jisilu.cn/question/ajax/get_answer_comments/answer_id-%s";

    public void collect(String url, String path, boolean onePage, boolean onlyPublish) {
        UrlBuilder urlBuilder = UrlBuilder.fromString(url);
        if (onlyPublish) {
            urlBuilder = urlBuilder.addParameter("uid", "publisher");
        }
        urlBuilder = urlBuilder.addParameter("sort_key", "add_time")
                .addParameter("sort", "DESC");
        Element body = Jsoup.parse(HttpUtils.httpGet(urlBuilder.toString()));
        JslQuestion jslQuestion = JslQuestion.parse(body);
        jslQuestion.setUrl(url);

        String name = FilenameUtils.getName(url);
        File picFile = FileUtils.getFile(path, name);

        //加100是因为有些没有回复也要保页面其他部分
        if (jslQuestion.getNumOfReply() == 0) {
            File file = new File(path, name + "-" + jslQuestion.getTitle().trim() + (onlyPublish ? "publisher" : "") + ".html");
            try {
                FileUtils.writeStringToFile(file, body.html(), StandardCharsets.UTF_8);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        for (int i = 1; i <= (jslQuestion.getNumOfReply() + 99) / 100; i++) {
            if (i != 1) {
                body = Jsoup.parse(HttpUtils.httpGet(String.format(questionPage, name, onlyPublish ? "publisher" : "", i)));
            }
            downPic(picFile, body);
            removeOther(body);
            Elements replyEles = body.select(".aw-dynamic-topic");
            //获取回复的 评论
            for (Element replyDiv : replyEles.get(0).children()) {
                addComment(replyDiv);
            }
            File file = new File(path, name + "-" + StringUtils.leftPad(i + "", 2, "0") + "-" + jslQuestion.getTitle().trim() + (onlyPublish ? "publisher" : "") + ".html");
            try {
                FileUtils.writeStringToFile(file, body.html(), StandardCharsets.UTF_8);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    protected Elements getReplyEles(File picFile, Element bodyFirst) {
        Elements replyElesFirst = bodyFirst.select(".aw-dynamic-topic");
        //获取回复的 评论
        for (Element replyDiv : replyElesFirst.get(0).children()) {
            addComment(replyDiv);
            downPic(picFile, replyDiv);
        }
        return replyElesFirst;
    }

    protected void downPic(File file, Element element) {
        Elements select = element.select(".aw-comment-upload-img-list a img");
        select.forEach(img -> {
            try {
                FileUtils.copyURLToFile(new URL(img.attr("src")), new File(file, FilenameUtils.getName(img.attr("src"))));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private void addComment(Element replyDiv) {
        String idStr = StringUtils.getDigits(replyDiv.attr("id"));
        //评论 数量
        Elements commentCount = replyDiv.select(".aw-add-comment");
        //没有评论
        if (commentCount.size() == 0) {
            return;
        }
        String digits = StringUtils.getDigits(commentCount.text());
        //有评论
        //2021年10月27日14:07:10 回复下面的评论不可见了。导致抓取报错
        if (!StringUtils.equals("0", digits) && SysUtils.isNumber(digits)) {
            String dataId = commentCount.get(0).attr("data-id");
            String ajaxComment = HttpUtils.httpGet(String.format(urlForComment, dataId));
            // id  从这里取数字，replyDiv.attr("id")
            Element commentBox = new Element("div").attr("class", "aw-comment-box").attr("id", "aw-comment-box-answer-" + (idStr));
            Element sondDiv = new Element("div").attr("class", "aw-comment-list").append(ajaxComment);
            commentBox.appendChild(sondDiv);
            replyDiv.appendChild(commentBox);
        }
    }

    /**
     * 移除其其它元素
     *
     * @param root 文档
     */
    public void removeOther(Element root) {
        //log 注册登录 右侧相关问题  回复编辑位置 底部位置  二维码
        String[] delClass = {".aw-logo", ".aw-login-register", ".aw-text-align-justify", ".aw-mod-replay-box", ".aw-footer-wrap", ".scanWeiXinWD"};
        for (String aClass : delClass) {
            root.select(aClass).remove();
        }
    }
}
